<template>
  <div class="main">
    <div class="login_form_circle"></div>
    <div class="login_form_circle2"></div>
    <div class="login_form_circle3"></div>
    <div class="login_form_circle4"></div>
    <div class="login_form">
      <a-row type="flex" :gutter="4" align="bottom" justify="center" >
        <a-col :span="12" >
          <div id="money" class="lottieDiv" ></div>
        </a-col>
        <a-col :span="12">
          <div class="main_loginform">
            <div class="login_title">
              欢迎登陆后台管理系统
            </div>
            <a-form
              id="formLogin"
              class="user-layout-login_form"
              ref="formLogin"
              :form="form"
              @submit="handleSubmit"
            >
              <a-tabs
                :activeKey="customActiveKey"
                :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
                @change="handleTabClick"
              >
                <a-tab-pane key="tab1" tab="账号密码">
                  <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" message="账号密码错误" />
                  <a-form-item>
                    <a-input
                      size="large"
                      type="text"
                      placeholder="请输入账号"
                      v-decorator="[
                        'username',
                        {rules: [{ required: true, message:'手机号码必须填写'}, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
                      ]"
                    >
                      <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                    </a-input>
                  </a-form-item>

                  <a-form-item>
                    <a-input-password
                      size="large"
                      placeholder="请输入密码"
                      v-decorator="[
                        'password',
                        {rules: [{ required: true, message: '密码必须填写' }], validateTrigger: 'blur'}
                      ]"
                    >
                      <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                    </a-input-password>
                  </a-form-item>
                </a-tab-pane>
                <a-tab-pane key="tab2" tab="验证码登陆">
                  <a-form-item>
                    <a-input size="large" type="text" :placeholder="$t('user.login.mobile.placeholder')" v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: $t('user.login.mobile.placeholder') }], validateTrigger: 'change'}]">
                      <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                    </a-input>
                  </a-form-item>

                  <a-row :gutter="16">
                    <a-col class="gutter-row" :span="16">
                      <a-form-item>
                        <a-input size="large" type="text" :placeholder="$t('user.login.mobile.verification-code.placeholder')" v-decorator="['captcha', {rules: [{ required: true, message: $t('user.verification-code.required') }], validateTrigger: 'blur'}]">
                          <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                        </a-input>
                      </a-form-item>
                    </a-col>
                    <a-col class="gutter-row" :span="8">
                      <a-button
                        class="getCaptcha"
                        tabindex="-1"
                        :disabled="state.smsSendBtn"
                        @click.stop.prevent="getCaptcha"
                        v-text="!state.smsSendBtn && $t('user.register.get-verification-code') || (state.time+' s')"
                      ></a-button>
                    </a-col>
                  </a-row>
                </a-tab-pane>
              </a-tabs>

              <!--              <a-form-item>-->
              <!--                <a-checkbox v-decorator="['rememberMe', { valuePropName: 'checked' }]">{{ $t('user.login.remember-me') }}</a-checkbox>-->
              <!--                <router-link-->
              <!--                  :to="{ name: 'recover', params: { user: 'aaa'} }"-->
              <!--                  class="forge-password"-->
              <!--                  style="float: right;"-->
              <!--                >{{ $t('user.login.forgot-password') }}</router-link>-->
              <!--              </a-form-item>-->

              <a-form-item style="margin-top:24px">
                <a-button
                  size="large"
                  type="primary"
                  htmlType="submit"
                  class="login-button"
                  :loading="state.loginBtn"
                  :disabled="state.loginBtn"
                >登陆</a-button>
              </a-form-item>
            </a-form>
          </div>
        </a-col>
      </a-row>
    </div>

  </div>
</template>

<script>
// import md5 from 'md5'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
// import { getSmsCaptcha, get2step } from '@/api/login'
import lottie from 'lottie-web'
import datajson from '@/assets/login.json'
export default {
  components: {
    TwoStepCaptcha
  },
  data () {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created () {
    // get2step({ })
    //   .then(res => {
    //     this.requiredTwoStepCaptcha = res.result.stepCode
    //   })
    //   .catch(() => {
    //     this.requiredTwoStepCaptcha = false
    //   })
    // this.requiredTwoStepCaptcha = true
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      const icon = document.getElementById('money')
      lottie.loadAnimation({
        container: icon, // 包含动画的dom元素
        renderer: 'svg', // 渲染出来的是什么格式
        loop: true, // 循环播放
        autoplay: true, // 自动播放
        animationData: datajson // 动画json的路径
      })
    },
    show () {
      lottie.play()
    },
    hidden () {
      lottie.stop()
    },
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit (e) {
      e.preventDefault()

      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true
      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']
      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          loginParams[!state.loginType ? 'email' : 'phone'] = values.username
          loginParams.password = (values.password)
          loginParams.type = 'web'
          console.log('登陆', loginParams)
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    // getCaptcha (e) {
    //   e.preventDefault()
    //   const { form: { validateFields }, state } = this
    //
    //   validateFields(['mobile'], { force: true }, (err, values) => {
    //     if (!err) {
    //       state.smsSendBtn = true
    //
    //       const interval = window.setInterval(() => {
    //         if (state.time-- <= 0) {
    //           state.time = 60
    //           state.smsSendBtn = false
    //           window.clearInterval(interval)
    //         }
    //       }, 1000)
    //
    //       const hide = this.$message.loading('验证码发送中..', 0)
    //       getSmsCaptcha({ mobile: values.mobile }).then(res => {
    //         setTimeout(hide, 2500)
    //         this.$notification['success']({
    //           message: '提示',
    //           description: '验证码获取成功，您的验证码为：' + res.result.captcha,
    //           duration: 8
    //         })
    //       }).catch(err => {
    //         setTimeout(hide, 1)
    //         clearInterval(interval)
    //         state.time = 60
    //         state.smsSendBtn = false
    //         this.requestFailed(err)
    //       })
    //     }
    //   })
    // },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed (err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.main{
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  //background-color: #0093E9;
  //background-image: linear-gradient(160deg, #0093E9 0%, #80D0C7 100%);
  background-image: linear-gradient( 135deg, #ABDCFF 0%, #0396FF 100%);
  .login_form_circle{
    width: 480px;
    height: 480px;
    border-radius: 50%;
    background-image: linear-gradient( 135deg, #5EFCE8 10%, #736EFE 100%);
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1;
    box-shadow: 1px 0 20px 2px rgba(0,0,0,.2);
    animation: dumpTopAndBottom 10s infinite;
  }
  .login_form_circle2{
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background-image: linear-gradient( 135deg, #2AFADF 10%, #4C83FF 100%);
    position: absolute;
    bottom: 100px;
    right: 100px;
    z-index: 1;
    box-shadow: 1px 0 20px 2px rgba(0,0,0,.2);
    animation: dumpLeftAndRight 10s infinite;
  }
  .login_form_circle3{
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-image: linear-gradient( 135deg, #5EFCE8 10%, #736EFE 100%);
    position: absolute;
    bottom: 400px;
    right: 300px;
    z-index: 1;
    box-shadow: 1px 0 20px 2px rgba(0,0,0,.2);
    animation: dumpTopAndBottom 10s infinite;
  }
  .login_form_circle4{
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background-image: linear-gradient( 135deg, #FCCF31 10%, #F55555 100%);
    position: absolute;
    top: 600px;
    left: 100px;
    z-index: 1;
    box-shadow: 1px 0 20px 2px rgba(0,0,0,.2);
    animation: dumpLeftAndRight 10s infinite;

  }
  @keyframes dumpTopAndBottom {
    0% {
      transform: translate(0px, 0px);
    }
    50% {
      transform: translate(0px, 30px);
    }
    100% {
      transform: translate(0px, 0px);
    }
  }
  @keyframes dumpLeftAndRight {
    0% {
      transform: translate(0px, 0px);
    }
    50% {
      transform: translate(30px, 0px);
    }
    100% {
      transform: translate(0px, 0px);
    }
  }
  .login_form{
    width: 80vw;
    height: 80vh;
    position: absolute;
    top: 10vh;
    left: 10vw;
    background-color: rgba(255,255,255,0.7);
    backdrop-filter: blur(8px);
    border-radius: 50px;
    padding: 50px;
    box-shadow: 1px 0 19px 6px rgba(0,0,0,.2);
    z-index:999;
    .lottieDiv{
      width: 800px;
    }
    .main_loginform{
      width: 60%;
      position: relative;
      top: -10vh;
      .login_title{
        margin: 0;
        font-size: 32px;
        font-weight: 600;
        color: #27386f;
        line-height: 24px;
        border-left: 4px solid #7984a6;
        padding-left: 10px;
      }
    }
  }
}
</style>
